package com.heima.article.kafka.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @作者 itcast
 * @创建日期 2020/9/28 15:35
 **/
@Component
@Slf4j
public class ArticleIsDownListener {
    @Autowired
    private ApArticleConfigService apArticleConfigService;
    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void receiveMessage(ConsumerRecord<?,?> record){
        log.info("文章微服务收到文章上下架通知==>"+record);
        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
        if (optional.isPresent()) {
            String message = (String) record.value();
            Map map = JSON.parseObject(message,Map.class);
            // 根据articleId作为查询条件
            // 将isDown字段改为enable对应的值
            apArticleConfigService.update(
                    Wrappers.<ApArticleConfig>lambdaUpdate()
                            .eq(ApArticleConfig::getArticleId,map.get("articleId"))
                            .set(ApArticleConfig::getIsDown,map.get("enable"))
            );
        }
    }
}
